/*
 * OntoTree.java
 *
 */

package ontoTree.ontoTree;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.mindswap.pellet.jena.PelletInfGraph;
import org.mindswap.pellet.jena.PelletReasonerFactory;

import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntResource;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JFormattedTextField;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import org.semanticweb.owl.align.Alignment;

/**
 * 
 * @author Ligia
 */
public class OntoTreeMain extends javax.swing.JFrame {
	private String path;
        private HashMap<String, AlignmentResult> alignResult = new HashMap<String, AlignmentResult>();
        HashMap <String, ArrayList> hashmaps = new HashMap <String, ArrayList>();
        
	/** Creates new form OntoTree */
	public OntoTreeMain() {
            
            AlignManagement aln = new AlignManagement();
            Alignment a1 = aln.openAlignmentFile("C:/Documents and Settings/Helio/Meus documentos/NetBeansProjects/MeMO/PesonAPesonB.rdf");
            aln.store(a1);
            hashmaps = aln.getAResult();
		initComponents();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed"
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        ontoPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        ontoTree1 = new javax.swing.JTree();
        btnOpenTree1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        ontoTree2 = new javax.swing.JTree();
        btnOpenTree2 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        btnMapNew = new javax.swing.JButton();
        btnMapEdit = new javax.swing.JButton();
        btnMapRemove = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setViewportView(ontoTree1);

        btnOpenTree1.setText("Abrir 1");
        btnOpenTree1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenTree1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ontoPanelLayout = new javax.swing.GroupLayout(ontoPanel);
        ontoPanel.setLayout(ontoPanelLayout);
        ontoPanelLayout.setHorizontalGroup(
            ontoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ontoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ontoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnOpenTree1))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        ontoPanelLayout.setVerticalGroup(
            ontoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ontoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 432, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnOpenTree1)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        jScrollPane2.setViewportView(ontoTree2);

        btnOpenTree2.setText("Abrir 2");
        btnOpenTree2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenTree2ActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Mapeamentos"));

        btnMapNew.setText("Novo");
        btnMapNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMapNewActionPerformed(evt);
            }
        });

        btnMapEdit.setText("Editar");
        btnMapEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMapEditActionPerformed(evt);
            }
        });

        btnMapRemove.setText("Remover");
        btnMapRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMapRemoveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnMapNew)
                .addGap(18, 18, 18)
                .addComponent(btnMapEdit)
                .addGap(18, 18, 18)
                .addComponent(btnMapRemove, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnMapNew)
                    .addComponent(btnMapEdit)
                    .addComponent(btnMapRemove))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(ontoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnOpenTree2)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(76, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(295, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(264, 264, 264))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 435, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnOpenTree2))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(ontoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(33, 33, 33)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(51, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnOpenTree2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenTree2ActionPerformed
ontoTree2 = chooseOntology().getOntologyTree();
		jScrollPane2.setViewportView(ontoTree2);
}//GEN-LAST:event_btnOpenTree2ActionPerformed

private void btnMapNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMapNewActionPerformed
            EditAlignmentDialog editAlign = new EditAlignmentDialog(this, true);
        
          
		editAlign.setVisible(true);
            String uri1 = getURIResource(ontoTree1);
            String uri2 = getURIResource(ontoTree2);
            if(editAlign.getReturnStatus() == editAlign.RET_OK){
                AlignmentResult align = new AlignmentResult();
                align.setUri1(uri1);
		align.setUri2(uri2);
		align.setRelationship(editAlign.getRelationship());
                
		align.setSimi(Double.parseDouble(editAlign.getSimi().replace(",", ".")));
               alignResult.put(uri1,align);
            }
                
		
}//GEN-LAST:event_btnMapNewActionPerformed

private void btnMapRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMapRemoveActionPerformed
    String uri1 = getURIResource(ontoTree1);
    if(alignResult.containsKey(uri1))
    alignResult.remove(uri1);
    
}//GEN-LAST:event_btnMapRemoveActionPerformed

private void btnMapEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMapEditActionPerformed
    String uri1 = getURIResource(ontoTree1);
    if(alignResult.containsKey(uri1)){
  AlignmentResult a = (AlignmentResult)alignResult.get(uri1);
  EditAlignmentDialog editAlign = new EditAlignmentDialog(this, true);
  editAlign.setRelationship(a.getRelation());
  editAlign.setSimi(a.getSimiString());
  editAlign.setVisible(true);
  
   if(editAlign.getReturnStatus() == editAlign.RET_OK){
                AlignmentResult align = new AlignmentResult();
                align.setUri1(uri1);
		align.setUri2(getURIResource(ontoTree2));
		align.setRelationship(editAlign.getRelationship());
		align.setSimi(Double.parseDouble(editAlign.getSimi()));
               alignResult.put(uri1, a);
            }
   
}
}//GEN-LAST:event_btnMapEditActionPerformed
 
String getURIResource(JTree tree){
      
     return ((OntResource) ((DefaultMutableTreeNode) tree
				.getSelectionPath().getLastPathComponent()).getUserObject())
				.getURI();
      
  }
	private void btnOpenTree1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnOpenTreeActionPerformed
		ontoTree1 = chooseOntology().getOntologyTree();
		jScrollPane1.setViewportView(ontoTree1);

	}// GEN-LAST:event_btnOpenTreeActionPerformed
        
        OntologyTree chooseOntology(){
            JFileChooser ontologyChooser = new JFileChooser();

		FileNameExtensionFilter filter = new FileNameExtensionFilter(
				"OWL e RDF", "owl", "rdf");

		ontologyChooser.setFileFilter(filter);
		ontologyChooser.setDialogTitle("Selecione uma ontologia em OWL ou RDF");
		ontologyChooser.setApproveButtonText("Abrir");
		int returnVal = ontologyChooser.showOpenDialog(null);
		if (returnVal == JFileChooser.APPROVE_OPTION) {

			path = ontologyChooser.getSelectedFile().getPath();
			path = path.replaceAll("\\\\", "/");
			
                           return new OntologyTree(loadOntology(path));
		

		} else
			
        
            return null;
        }

	OntModel loadOntology(String path) {
		String fileOnt = "file:" + path;
		
		try{

		// cria o reasoner
		OntModel model = ModelFactory
				.createOntologyModel(PelletReasonerFactory.THE_SPEC);

		// cria o modelo para ontologia
		System.out.print("Lendo...");
		model.read(fileOnt);
		System.out.println("Concluido ---> Leitura");

		// carrega o modelo para o reasoner
		System.out.print("Preparando...");
		model.prepare();
		System.out.println("Concluido ---> Preparacao");

		// computa a �rvore de classifica��o
		System.out.print("Classificando...");
		((PelletInfGraph) model.getGraph()).getKB().classify();
		System.out.println("Concluido ----> Classificacao");
		
		return model;
                
		}catch(Exception e){
			JOptionPane.showMessageDialog(null, e.toString());
                        return null;
		}

	
	
	}
        


	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new OntoTreeMain().setVisible(true);
			}
		});
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnMapEdit;
    private javax.swing.JButton btnMapNew;
    private javax.swing.JButton btnMapRemove;
    private javax.swing.JButton btnOpenTree1;
    private javax.swing.JButton btnOpenTree2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPanel ontoPanel;
    private javax.swing.JTree ontoTree1;
    private javax.swing.JTree ontoTree2;
    // End of variables declaration//GEN-END:variables

}
